package servlet.universal;


import service.UserService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author huangzhiyang
 * @Date 2023/9/19
 */
@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        //获取传过来的值
        String user = request.getParameter("user");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String msg = "{\"msg\":\"fail\"}";
        try {
            if (UserService.login(user, username, password) != null) {
                //  登录成功
                msg = "{\"msg\":\"success\"}";
                // 建立cookie
                Cookie cookie1 = new Cookie("user", user);
                Cookie cookie2 = new Cookie("username", username);
                // 添加SameSite属性（通过Set-Cookie响应头）
                String cookieValue1 = cookie1.getName() + "=" + cookie1.getValue() + "; SameSite=Lax";
                String cookieValue2 = cookie2.getName() + "=" + cookie2.getValue() + "; SameSite=Lax";
                response.setHeader("Set-Cookie", cookieValue1);
                response.addHeader("Set-Cookie", cookieValue2);
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            } else {
                //  登录失败
                response.sendRedirect("login.html?Result=false");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //给前端响应数据
        response.getWriter().write(msg);
        System.out.println("finish");
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        System.out.println("LoginServlet现在来了一个post请求，将要去走get的代码了。");
        doGet(request, response);

    }


}

